<template>
  <view class="project-detail">
    <project-info-title :projectName="projectName" :online="online" :activeTab="activeTab" @toggleTab="tabChange($event)"></project-info-title>
    <view class="detail-content">
      <project-info v-show="activeTab === PROJECT_TAB.INFO" ref="info" :projectInfo="projectInfo" @refresh="getProjectInfo(true)"></project-info>
      <lamp-detail v-show="activeTab === PROJECT_TAB.LAMP" ref="lamp" :projectInfo="projectInfo" @refresh="getProjectInfo(true)"></lamp-detail>
      <project-gateway v-show="activeTab === PROJECT_TAB.GATEWAY" ref="gateway" :projectInfo="projectInfo"></project-gateway>
      <project-meter v-show="activeTab === PROJECT_TAB.METER" ref="meter" :projectInfo="projectInfo"></project-meter>
      <members v-show="activeTab === PROJECT_TAB.MEMBERS" ref="members" :projectInfo="projectInfo" @refresh="getProjectInfo(true)" @openShare="shareProject()" @closeShare="closeShare()"></members>
    </view>
    <uni-popup
      class="share-dialog"
      ref="shareDialog"
      type="center">
      <share-project ref="share" :projectInfo="projectInfo" @close="closeShare" @share="onShare()"></share-project>
    </uni-popup>
  </view>
</template>

<script>
import mixin from '@/mixins/index.js'
import { getImagePath, getVideoPath, fixedDecimal, getCarbonReductionByPower, formatNumber, formatDate } from '@/utils/index.js'
import { PROJECT_TAB, FILE_TYPE } from '@/constant/index.js'
import ProjectInfoTitle from './components/project-info-title/project-info-title.vue'
import ProjectInfo from './components/info/info.vue'
import LampDetail from './components/lamp-detail/lamp-detail.vue'
import ProjectGateway from './components/gateway/gateway.vue'
import ProjectMeter from './components/meter/meter.vue'
import Members from './components/members/members.vue'
import ShareProject from './components/share/share.vue'

export default {
  components: {
    ProjectInfoTitle,
    ProjectInfo,
    LampDetail,
    ProjectGateway,
    ProjectMeter,
    Members,
    ShareProject
  },
  mixins: [mixin],
  data() {
    return {
      activeTab: PROJECT_TAB.INFO,
      projectName: '',
      online: true,
      userInfo: null,
      projectInfo: {},
      PROJECT_TAB,
      shareInfo: {
        shareKey: ''
      }
    }
  },
  onShow() {
    this.getProjectInfo()
    this.startLampScan()
  },
  onHide() {
    this.endLampScan()
  },
  onUnload() {
    this.endLampScan()
  },
  onPullDownRefresh() {
    this.getProjectInfo(true)
  },
  onShareAppMessage() {
    const self = this
    return {
      title: `${self.userInfo.name}邀请你加入项目`,
      path: `/pages/entrance/share/share?key=${self.shareInfo.shareKey}`
    }
  },
  mounted() {
    this.getProjectInfo()
  },
  methods: {
    getProjectInfo(refresh) {
      const self = this
      uni.request({
        url: '/project/get',
        data: {
          id: self.params.id
        },
        success(result) {
          if (result.data.success && result.data.data) {
            const projectInfo = result.data.data
            projectInfo.name = projectInfo.name || ''
            projectInfo.online = !!projectInfo.online
            projectInfo.isOwner = projectInfo.user_id === self.userInfo?.id
            projectInfo.canEdit = projectInfo.isOwner || self.canEdit
            projectInfo.projectAdmin = projectInfo.members?.find((user) => user.user_id === projectInfo.user_id)
            projectInfo.projectAdminName = projectInfo.projectAdmin?.user_name
            projectInfo.projectAdminPhone = projectInfo.projectAdmin?.phone
            projectInfo.projectAddress = projectInfo.address || ''
            projectInfo.gatewayNumber = projectInfo.gateway_id || ''
            projectInfo.lampTotalCount = Math.ceil(projectInfo._node_count) || 0
            projectInfo.lampWarningCount = Math.ceil(projectInfo._error_count + projectInfo._warning_count) || 0
            projectInfo.powerTotal = fixedDecimal(projectInfo._KWh, 2) || 0
            projectInfo.savingRate = fixedDecimal(projectInfo._rate, 2) || 0
            projectInfo.powerSaving = fixedDecimal((projectInfo.powerTotal * projectInfo.savingRate) / (100 - projectInfo.savingRate), 2)
            projectInfo.carbonReduction = getCarbonReductionByPower(projectInfo.powerSaving)
            projectInfo.price = fixedDecimal(projectInfo.price, 4)
            projectInfo.moneySave = formatNumber(projectInfo.powerSaving * projectInfo.price)
            projectInfo.setupTime = ''
            if (Array.isArray(projectInfo.gateway) && projectInfo.gateway[0]?.install_time) {
              projectInfo.setupTime = formatDate(projectInfo.gateway[0]?.install_time, 'yyyy年MM月dd日')
            }
            projectInfo.demoList = []
            if (projectInfo.imgs) {
              try {
                const imgs = JSON.parse(projectInfo.imgs)
                if (Array.isArray(imgs)) {
                  imgs.forEach((item) => {
                    if (item.type === FILE_TYPE.IMAGE) {
                      item.src = getImagePath(item.path)
                    } else if (item.type === FILE_TYPE.VIDEO) {
                      item.src = getVideoPath(item.path)
                    }
                  })
                  projectInfo.demoList = imgs
                }
              } catch (e) {
                console.error(e)
              }
            }
            projectInfo.lampMapList = []
            if (Array.isArray(projectInfo.pic)) {
              projectInfo.pic.forEach((item) => {
                item.name = item.name || ''
                item.key = item.id
                item.src = getImagePath(item.img_path)
              })
              projectInfo.lampMapList = projectInfo.pic
            }
            self.projectName = projectInfo.name
            self.online = projectInfo.online
            self.projectInfo = projectInfo
            if (refresh) {
              self.refreshChildPage()
            }
          }
        },
        complete() {
          uni.stopPullDownRefresh()
        }
      })
    },
    refreshChildPage() {
      const self = this
      const cases = {
        [PROJECT_TAB.INFO]: self.$refs.info,
        [PROJECT_TAB.LAMP]: self.$refs.lamp,
        [PROJECT_TAB.GATEWAY]: self.$refs.gateway,
        [PROJECT_TAB.METER]: self.$refs.meter,
        [PROJECT_TAB.MEMBERS]: self.$refs.members,
      }
      cases[self.activeTab].initData()
    },
    tabChange(targetTab) {
      const self = this
      if (self.activeTab === targetTab) return
      self.activeTab = targetTab
      if (targetTab === PROJECT_TAB.LAMP) {
        self.startLampScan()
      } else {
        self.endLampScan()
      }
    },
    startLampScan() {
      if (this.activeTab === PROJECT_TAB.LAMP) {
        this.$refs.lamp.startLampScan()
      }
    },
    endLampScan() {
      this.$refs.lamp.endLampScan()
    },
    shareProject() {
      const self = this
      self.generateShareKey()
        .then(() => {
          self.$refs.shareDialog.open()
        })
    },
    generateShareKey() {
      const self = this
      return new Promise((resolve) => {
        uni.request({
          url: '/project/gen_share_info',
          method: 'GET',
          data: {
            xm_id: self.projectInfo.id,
            permission: '',
          },
          success(result) {
            if (result.data.success && result.data.data) {
              self.shareInfo.shareKey = result.data.data
              resolve()
            }
          }
        })
      })
    },
    getShareActiveId() {
      const self = this
      return new Promise((resolve) => {
        uni.request({
          url: '/user/activityid',
          method: 'GET',
          data: {},
          success(result) {
            if (result.data.success) {
              self.shareInfo.activeId = result.data.activity_id
              wx.updateShareMenu({
                withShareTicket: true,
                isPrivateMessage: true,
                activityId: self.shareInfo.activeId,
              })
              resolve()
            }
          }
        })
      })
    },
    closeShare() {
      const self = this
      self.$refs.shareDialog.close()
    },
    onShare() {
      this.closeShare()
    }
  }
}
</script>

<style lang="scss" scoped>
.detail-content {
  position: relative;
  padding: 20rpx 30rpx 120rpx;
}
</style>
